<template>
  <div>
    <div class="personal xui-padding-sm">
      <div class="title">
        <span class="color-darken-gray">讲座活动：</span>
        <span>{{title}}</span>
      </div>
      <div class="title">
        <span class="color-darken-gray">日期场次：</span>
        <span>{{date | parseTime}}</span>
        <span>{{period}}</span>
      </div>
      <div class="xui-margin-vertical-sm content">
        <div v-for="(item,index) in data" :key="'form'+index">
          <el-form :model="item" class="demo-form-inline" :rules="rules" size="small " :ref="`form-${index}`">
            <el-form-item label=" " prop="persontype">
              <el-select v-model="item.persontype" placeholder="类型" class="type" @change="changeType(index)">
                <el-option v-for="item in detail.arraySocial" :label="item" :value="item" :key="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label=" " prop="joinUserName">
              <el-input v-model="item.joinUserName" placeholder="姓名"></el-input>
            </el-form-item>
            <div class="person" v-if="item.persontype === '成人' ">
              <el-form-item label=" " prop="cardType">
                <el-select v-model="item.cardType" placeholder="证件" class="select">
                  <el-option v-for="item in cardTypes" :label="item" :value="item" :key="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label=" " prop="cardNum">
                <el-input v-model="item.cardNum" placeholder="证件号码"></el-input>
              </el-form-item>
              <el-form-item label=" " prop="mobile">
                <el-input v-model="item.mobile" placeholder="手机号码"></el-input>
              </el-form-item>
            </div>
            <div class="student" v-else>
              <el-form-item label=" " prop="grade">
                <el-select v-model="item.grade" placeholder="年级" class="select">
                  <el-option v-for="item in detail.arrayClass" :label="item" :value="item" :key="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label=" " prop="school">
                <el-input v-model="item.school" placeholder="学校"></el-input>
              </el-form-item>
              <el-form-item label=" " prop="age">
                <el-input v-model="item.age" placeholder="年龄"></el-input>
              </el-form-item>
            </div>
            <el-form-item label=" " prop="email" width="100px">
              <el-input v-model="item.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <span v-if="data.length > 1" class="cursor-point color-red delete-btn" style="display:inline-block;width:40px;line-height:32px"
              @click="remove(index)">删除</span>
          </el-form>
        </div>

        <el-button v-if="data.length < 2" type="primary" icon="el-icon-circle-plus-outline" circle @click="add()" size="small">添加预约人</el-button>
        <span class="color-red xui-margin-bottom-sm">温馨提醒：最多填两个参与人（每个参与人占一个名额）</span>
        <div class="title quit-title"><span class="quit">观众提问</span>
          <el-input type="textarea" :rows="2" :maxlength="500" placeholder="请输入内容" v-model="quiz">
          </el-input>

        </div>
        <div class="dialog-footer xui-margin-top xui-text-center">
          <el-button type="primary" @click="submitPerson()" v-loading="loading">确定预约</el-button>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
  import {
    personAppoint,
    getStudentGrades
  } from "@/api/act";
  import {
    getToken
  } from "@/utils/auth";
  import {
    getCardType
  } from "@/api/login";
  import {
    parseTime
  } from "@/utils";

  export default {
    props: ["date", "id", "playId", "title", "detail", "period"],
    data() {
      return {
        quiz: '',
        grades: [],
        allSelectInput: [],
        componentName: "",
        cardTypes: [],
        data: [],
        rules: {
          persontype: [{
            required: true,
            message: "请选择用户类型",
            trigger: "blur"
          }],
          joinUserName: [{
            required: true,
            message: "请输入姓名",
            trigger: "blur"
          }],
          cardType: [{
            required: true,
            message: "请选择证件类型",
            trigger: "change"
          }],
          cardNum: [{
              required: true,
              message: "请填写证件号码",
              trigger: "blur"
            },
            {
              type: "",
              message: "请输入正确的证件号码",
              trigger: "blur"
            }
          ],
          mobile: [{
              required: true,
              message: "请填写手机号码",
              trigger: "blur"
            },
            {
              pattern: /^1[3|4|5|6|8|7][0-9]\d{4,8}$/,
              message: "请填写正确的手机号码",
              trigger: "blur"
            }
          ],
          grade: [{
            required: true,
            message: "选择年级",
            trigger: "change"
          }],
          school: [{
            required: true,
            message: "请填写学校",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            message: "请填写正确的邮箱地址",
            trigger: "blur"
          }]
        },
        loading: false
      };
    },
    computed: {
      userId() {
        return this.$store.getters.userId;
      },
      token() {
        return getToken();
      },
      userInfo() {
        return this.$store.getters.userInfo;
      }
    },
    methods: {
      add() {
        let length = this.allSelectInput.length;
        let arr = this.data;
        if (arr.length < 2) {
          arr.push({
            persontype: this.detail.arraySocial[0],
            joinUserName: "",
            cardType: "",
            cardNum: "",
            mobile: "",
            email: "",
            grade: "",
            school: "",
            age: ""
          });
        } else {
          this.$message({
            showClose: true,
            type: "error",
            message: "最多只能添加2个联系人哦"
          });
        }
      },
      remove(index) {
        let arr = this.data;
        if (arr.length > 1) {
          arr.splice(index, 1);
        } else {
          return false;
        }
      },
      submitPerson() {
        let isValid = this.data.every((item, index) => {
          let result;
          this.$refs["form-" + index][0].validate(valid => {
            if (valid) {
              result = true;
            } else {
              result = false;
            }
          });
          return result;
        });
        if (!isValid) {
          this.$message({
            showClose: true,
            type: "error",
            message: "请填写正确信息后重试"
          });
          return false;
        }

        // 验证通过后执行提交步骤
        this.loading = true;
        let pData = {
          sourceId: "WEB",
          token: this.token,
          lectureDate: this.date,
          userId: this.userId,
          vid: this.id,
          playId: this.playId,
          data: this.data,
          persontype: this.persontype,
          message: this.quiz
        };
        personAppoint(pData)
          .then(res => {
            this.loading = false;
            console.log(this.loading);
            if (res.flag == 1) {
              this.$message({
                showClose: true,
                type: "success",
                message: res.msg.length > 0 ?
                  res.msg + "您可以在个人中心查看预约信息" : "预约成功，您可以在个人中心查看预约信息"
              });
              if (res.msg == "请求成功") {
                this.$emit("appointed", res.data);
              }
            } else if (res.flag == -1) {
              this.loading = false;
              console.log(res.flag, this.loading);
              this.$message({
                showClose: true,
                type: "error",
                message: res.msg || "提交失败，请重试"
              });
            }
          })
          .catch(err => {
            this.loading = false;
            console.log(err);
          });
      },
      getCardType() {
        getCardType().then(res => {
          res.data.recordsList.forEach(item => {
            this.cardTypes.push(item.dictName);
          });
        });
      },
      appointSuccess(msg) {
        this.$emit("personSuccess", msg);
      },
      getGrades() {
        getStudentGrades().then(res => {
          res.data.forEach(item => {
            this.grades.push(item.menuName);
          });
        });
      },
      fillUserInfo() {
        let userInfo = {
          persontype: this.detail.arraySocial[0],
          joinUserName: this.userInfo.userName,
          cardType: this.userInfo.codeType,
          cardNum: this.userInfo.code,
          mobile: this.userInfo.mobile,
          email: this.userInfo.email,
          grade: "",
          school: "",
          age: this.userInfo.age
        };
        this.data.push(userInfo);
      },
      changeType(index) {
        let form = this.$refs["form-" + index][0];
        form.clearValidate();
      }
    },
    filters: {
      parseTime(value) {
        let arr = value.split("-");
        return `${arr[0]}年${arr[1]}月${arr[2]}日`;
      }
    },
    mounted() {
      this.getCardType();
      // this.getGrades();
      this.fillUserInfo();
    }
  };

</script>
<style lang="less" scoped>
  .personal {
    background-color: #fafafa;
  }

  .title {
    margin-bottom: 5px;
    color: #333;

    span {
      font-size: 15px;
      color: #aa8336;
    }
  }

  .content {
    >span {
      display: block;
    }
  }

  .demo-form-inline {
    display: flex;
    margin-top: 20px;
  }

  .person,
  .student {
    display: flex;

    >span {
      width: 50px;
      margin: 8px 10px 0 10px;
    }
  }

  .type {
    width: 80px;
  }

  .select {
    width: 100px;
  }

  .el-form-item {
    display: flex;
  }

  .el-input,
  .el-select {
    margin-left: -10px;
    margin-right: 16px;
  }

  .delete-btn:hover {
    color: red - #222222;
  }

  .quit-title {
    position: relative;
    bottom: 8px;

    .el-textarea {
      margin-top: 10px;
    }

    .quit {
      font-size: 15px;
      color: #666 !important;
    }
  }

</style>
